import { Button, Form, Input } from 'antd';
import { useLocation } from 'react-router-dom';

import usersApi from '@/api/usersApi';
import { message } from '@/components/AntdGlobal';
import { useUserStore } from '@/store';
import type { ILogin } from '@/types/api';

import styles from './index.module.less';

// 定义表单字段的类型
type FieldType = Partial<ILogin.Params>;

const Login = () => {
    /* 数据管理--------------------------------------------------- */
    const updateToken = useUserStore((state) => state.updateToken);
    const [loading, setLoading] = useState(false);
    const { search } = useLocation();
    const navigate = useNavigate();
    /* hooks ---------------------------------------------------- */

    /* 函数定义 ---------------------------------------------------*/
    /**
     * 表单提交且数据验证成功完成
     *
     * @param data 表单提交的值
     */
    const onFinish = async (data: ILogin.Params) => {
        setLoading(true);
        try {
            const res = await usersApi.login(data);
            const token = res.data;
            setLoading(false);

            // 更新token,并存储到本地
            updateToken(token);
            message.success('登录成功');

            // 解析query参数的callback地址,实现登录成功自动跳转。
            // 例如：http://www.baidu.com/login?callback=http://www.baidu.com/userList
            const params = new URLSearchParams(search);
            const callback = params.get('callback');
            const target = callback ? decodeURIComponent(callback) : '/welcome';

            // 延迟执行，确保token种植成功再跳转
            setTimeout(() => {
                navigate(target, { replace: true });
            }, 300);
        } catch (error: any) {
            message.error(error?.message || '登录失败,请稍后再试!');
            setLoading(false);
        }
    };

    return (
        <div className={styles.login}>
            <div className={styles.loginWrapper}>
                <div className={styles.title}>系统登录</div>
                <Form
                    name="login"
                    autoComplete="off"
                    labelCol={{ span: 4 }}
                    wrapperCol={{ span: 20 }}
                    onFinish={onFinish}
                    labelAlign="left"
                >
                    <Form.Item<FieldType>
                        label="用户名"
                        name="username"
                        rules={[
                            {
                                required: true,
                                message: 'Please input your username!'
                            }
                        ]}
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item<FieldType>
                        label="密码"
                        name="password"
                        rules={[
                            {
                                required: true,
                                message: 'Please input your password!'
                            }
                        ]}
                    >
                        <Input.Password />
                    </Form.Item>
                    <Form.Item label={null}>
                        <Button
                            block
                            type="primary"
                            htmlType="submit"
                            loading={loading}
                        >
                            登录
                        </Button>
                    </Form.Item>
                </Form>
            </div>
        </div>
    );
};

export default Login;
